package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OrderVerificationActivity extends AppCompatActivity {
    private TextView tvSelectedInfo, tvCurrentTime, tvTotalOrder, tvCheckedOrder;
    private Button btnSelectTime;
    private List<String> arriveTimeList = new ArrayList<>(); // 用餐时间列表
    private String selectedTime; // 当前选择的时间
    private int schoolId; // 学校ID
    private OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_verification);

        // 初始化控件
        tvSelectedInfo = findViewById(R.id.tvSelectedInfo);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalOrder = findViewById(R.id.tvTotalOrder);
        tvCheckedOrder = findViewById(R.id.tvCheckedOrder);
        btnSelectTime = findViewById(R.id.btnSelectTime);

        // 接收上一页数据（需确保MainActivity传递了以下参数）
        String cityName = getIntent().getStringExtra("cityName");
        String schoolName = getIntent().getStringExtra("schoolName");
        String campusName = getIntent().getStringExtra("campusName");
        schoolId = getIntent().getIntExtra("schoolId", 0);
        arriveTimeList = getIntent().getStringArrayListExtra("arriveTimes");

        // 显示选择信息
        tvSelectedInfo.setText(String.format("· 城市：%s\n· 学校：%s\n· 校区：%s",
                cityName, schoolName, campusName));

        // 默认选择第一个时间点（如果有数据）
        if (!arriveTimeList.isEmpty()) {
            selectedTime = arriveTimeList.get(0);
            tvCurrentTime.setText(selectedTime);
            fetchOrderData(selectedTime); // 自动加载数据
        }

        // 时间选择按钮点击事件
        btnSelectTime.setOnClickListener(v -> showTimeDialog());
    }

    private void showTimeDialog() {
        if (arriveTimeList.isEmpty()) {
            Toast.makeText(this, "无可用用餐时间", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("选择用餐时间")
                .setItems(arriveTimeList.toArray(new String[0]), (dialog, which) -> {
                    selectedTime = arriveTimeList.get(which);
                    tvCurrentTime.setText(selectedTime);
                    fetchOrderData(selectedTime); // 选择后重新加载数据
                })
                .show();
    }

    private void fetchOrderData(String time) {
        // 构造请求参数（eid=学校ID，arrive_time=选择的时间）
        FormBody body = new FormBody.Builder()
                .add("eid", String.valueOf(schoolId))
                .add("arrive_time", time)
                .build();

        Request request = new Request.Builder()
                .url("https://school.lihua.com/api/cashier/getorderlist")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(OrderVerificationActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String resp = response.body().string();
                    try {
                        JSONObject json = new JSONObject(resp);
                        if (json.getInt("code") == 1) { // 接口返回code=1表示成功
                            JSONObject data = json.getJSONObject("data");
                            int total = data.getInt("count");
                            int checked = data.getInt("checkednum");
                            runOnUiThread(() -> updateOrderData(total, checked));
                        } else {
                            runOnUiThread(() -> {
                                try {
                                    Toast.makeText(OrderVerificationActivity.this, "接口错误：" + json.getString("msg"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(OrderVerificationActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show());
                    }
                }
            }
        });
    }

    private void updateOrderData(int total, int checked) {
        tvTotalOrder.setText("总订单：" + total);
        tvCheckedOrder.setText("已核销：" + checked);
    }
}